package com.mimo.push.service.impl;

import java.util.Objects;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.mimo.common.listener.IMessage;
import com.mimo.common.room.event.RoomEventType;
import com.mimo.common.room.event.RoomTopicEvent;
import com.mimo.common.rpc.proto.LogicRoomRpc.ClientRoomOpsMessage;
import com.mimo.common.utils.JsonUtils;
import com.mimo.push.config.LogicRoomPoolFactory;
import com.mimo.push.service.IRoomService;

@Service
public class RoomServiceImpl implements IRoomService, IMessage {

  @Autowired
  private LogicRoomPoolFactory logicRoomPoolFactory;

  @Resource
  private IRoomService selfService;

  @Value("${logic.room.channel}")
  private String channel;

  @Override
  @Cacheable(cacheNames = "push:user:room", unless = "#result==null")
  public Boolean isMemberOf(String roomId, String userId) {
    return logicRoomPoolFactory.getLogicRoomStub()
        .isMemberOf(ClientRoomOpsMessage.newBuilder().setRoomId(roomId).setUserId(userId).build()).getValue();
  }

  @Override
  public void onMessage(String event) {
    RoomTopicEvent evt = JsonUtils.parseJson(event, RoomTopicEvent.class);
    if (Objects.equals(evt.getType(), RoomEventType.MemberLeft)) { // 如果为用户离群消息通知，则实时移除本地缓存
      selfService.leave(evt.getRoomId(), evt.getMember());
    }
  }

  @Override
  public String getTopic() {
    return channel;
  }

  @Override
  @CacheEvict(cacheNames = "push:user:room")
  public void leave(String roomId, String userId) {
    // nothing to do here
  }

}
